#include "ExpAST.h"
#include "Globe.h"
#include <iostream>
#include "parser.h"
#include "Globe.h"
#pragma warning(disable:4267)
using std::cout;
using std::endl;

unique_ptr<BaseExpAST> parser::parseEqExp()
{
    unique_ptr<BaseExpAST>l = this->parseRelExp();
    while (this->lexer->next_token() == TOK::EQ || this->lexer->next_token() == TOK::NE)
    {
        unique_ptr<EqAST>t(new EqAST);
        switch (this->lexer->next_token())
        {
        case TOK::EQ:
            t->op = EqAST::EQ;
            break;
        case TOK::NE:
            t->op = EqAST::NE;
            break;
        default:
            break;
        }
        this->lexer->match(this->lexer->next_token());
        t->exp1 = std::move(l);
        t->exp2 = this->parseRelExp();
        l = std::move(t);
        t = nullptr;
    }
    return l;
}

void EqAST::Dump() const
{
    cout << "{\"type\":\"Eq\",\"op\":\"";
    switch (this->op)
    {
    case EQ:
        cout << "==";
        break;
    case NE:
        cout << "!=";
        break;
    default:break;
    }
    cout << "\"";
    if (this->op == DEFAULT)
    {
        cout << "\"content\":";
        this->exp1->Dump();
    }
    else
    {
        cout << "\"exp1\":";
        this->exp1->Dump();
        cout << ",\"exp2\":";
        this->exp2->Dump();
    }
    cout << "}";
}


bool EqAST::is_lval() const
{
    if (this->op == DEFAULT)
        return this->exp1->is_lval();
    return false;
}

void EqAST::Analyze() const
{
    if (this->op == EqAST::DEFAULT)
        this->exp1->Analyze();
    else
    {
        this->exp2->Analyze();
        GENASM(cmd_code::PUSH, CVR(EAX), cmd_val());
        this->exp1->Analyze();
        GENASM(cmd_code::POP, CVR(EDX), cmd_val());
        GENASM(cmd_code::CMP, CVR(EAX), CVR(EDX));
        if (this->op == EqAST::EQ) {
            GENASM(cmd_code::SETE, CVR(AL), cmd_val());
        }
        else {
            GENASM(cmd_code::SETNE, CVR(AL), cmd_val());
        }
        GENASM(cmd_code::MOVZBL, CVR(AL), CVR(EAX));
    }
}
